package com.tai.network;

import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * The type Tcp demo.
 *
 * @Desc : tcpdemo
 * @Author ： taylor
 * @Date ：2021/6/23 22:43
 */
public class TCPDemo {

    /**
     * Client.
     *
     * @throws IOException the io exception
     */
    @Test
    public void client() throws IOException {
        try (Socket client = new Socket(InetAddress.getByName("localhost"), 8888);
             OutputStream os  = client.getOutputStream()) {
            //向服务端发送消息
            os.write("你好：小姐姐！".getBytes());

            //指示说明消息已发完
            client.shutdownOutput();

            //接受服务端的回复
            InputStream inputStream = client.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len=inputStream.read(buffer))!= -1 ){

                byteArrayOutputStream.write(buffer,0,len);
            }
            System.out.println(byteArrayOutputStream.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * Server.
     */
    @Test
    public void server(){
        try (ServerSocket serverSocket = new ServerSocket(8888);
             Socket socket =serverSocket.accept()) {

            //接受客户端发送的信息
            InputStream inputStream = socket.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len=inputStream.read(buffer))!= -1 ){

                byteArrayOutputStream.write(buffer,0,len);
            }
            System.out.println(byteArrayOutputStream.toString());

            //回复客户端消息
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("你好：小哥哥！你的信息已收到".getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
